package cn.yunhe.util;


import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

public class GetVeryCodeUtil {

    public static HashMap<String,String> sendMessage(String phoneNumber) {
        HashMap<String,String> hashMap=new HashMap<>();
        Random random = new Random();
        String res="";
        for (int i=0;i<6;i++)
        {
            res+=random.nextInt(10);
        }

        String resulta ="\""+res+"\"";

        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://api.sms.cn/sms/");
        // PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");
        post.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=UTF-8");// 在头文件中设置转码1
        NameValuePair[] data = {
                new NameValuePair("ac", "send"),
                new NameValuePair("uid", "gesen123"),// 注册的用户名
                new NameValuePair("pwd", "ee67c0cc824bc44daaabf90a379e5c79"),// 注册成功后，登录网站后得到的密钥
                new NameValuePair("mobile", phoneNumber),// 手机号码
                new NameValuePair("template","437819"),
                new NameValuePair("content","{\"code\":"+resulta+"}")};// 短信内容
        post.setRequestBody(data);
        try {
            client.executeMethod(post);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        String result=null;

        try {
            result = new String(post.getResponseBodyAsString().getBytes(
                    "UTF-8"));
            hashMap.put("result",result);
            hashMap.put("code",resulta);
            return hashMap;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
